' Stephen Toub
' Coded and published in January 2007 issue of MSDN Magazine 
' http://msdn.microsoft.com/msdnmag/issues/07/01/PreviewHandlers/default.aspx


Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Windows.Forms
Imports System.Runtime.InteropServices
Imports System.Reflection
Imports System.Text
Imports C4F.DevKit.PreviewHandler.PreviewHandlerFramework

Namespace C4F.DevKit.PreviewHandler.PreviewHandlers
    <PreviewHandler("MSDN Magazine Strong Name Key Preview Handler", ".snk;.keys", "{D7CAD297-1D39-478d-8BCC-585D74B234DA}"), ProgId("C4F.DevKit.PreviewHandler.PreviewHandlers.SnkPreviewHandler"), Guid("2D6DAD69-F296-4be0-AB9E-6ED642AEF76B"), ClassInterface(ClassInterfaceType.None), ComVisible(True)> _
    Public NotInheritable Class SnkPreviewHandler
        Inherits FileBasedPreviewHandler
        Protected Overrides Function CreatePreviewHandlerControl() As PreviewHandlerControl
            Return New SnkPreviewHandlerControl()
        End Function

        Private NotInheritable Class SnkPreviewHandlerControl
            Inherits StreamBasedPreviewHandlerControl
            Public Overrides Sub Load(ByVal stream As Stream)
                Dim snk As StrongNameKeyPair = New StrongNameKeyPair(CType(stream, FileStream))
                Dim text As TextBox = New TextBox()
                text.Dock = DockStyle.Fill
                text.ReadOnly = True
                text.Multiline = True
                text.Text = "Public key:" & Environment.NewLine & ToHexString(snk.PublicKey)
                Controls.Add(text)
            End Sub

            Private Shared Function ToHexString(ByVal bytes As Byte()) As String
                Dim sb As StringBuilder = New StringBuilder(bytes.Length * 2)
                For i As Integer = 0 To bytes.Length - 1
                    Dim val As Integer = bytes(i)
                    sb.Append(GetHexValue(val >> 4))
                    sb.Append(GetHexValue(val And &HF))
                Next i
                Return sb.ToString()
            End Function

            Private Shared Function GetHexValue(ByVal val As Integer) As Char
                If val < 10 Then
                    Return ChrW(CInt(Fix("0"c)) + val)
                ElseIf val >= 10 AndAlso val <= 15 Then
                    Return ChrW(CInt(Fix("A"c)) + (val - 10))
                Else
                    Throw New ArgumentOutOfRangeException("val")
                End If
            End Function
        End Class
    End Class
End Namespace